/**
 * Copyright &copy; 2017 <a href="https://gitee.com/hackempire/emsite-parent">emsite</a> All rights reserved.
 */
package com.empire.emsite.modules.sys.service;

import java.util.Collection;
import java.util.Date;

import org.apache.shiro.session.Session;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.empire.emsite.common.security.shiro.session.SessionDAO;
import com.empire.emsite.common.utils.StringUtils;
import com.empire.emsite.common.web.Servlets;
import com.empire.emsite.modules.sys.entity.User;
import com.empire.emsite.modules.sys.facade.SystemFacadeService;
import com.empire.emsite.modules.sys.security.SystemAuthorizingRealm;
import com.empire.emsite.modules.sys.utils.UserUtils;

/**
 * 类SystemServiceUtils.java的实现描述：系统管理，安全相关实体的管理类,包括用户、角色、菜单.
 * 
 * @author arron 2017年10月30日 下午7:19:44
 */
@Service
public class SystemServiceUtils implements InitializingBean {

    public static final String     HASH_ALGORITHM   = "SHA-1";
    public static final int        HASH_INTERATIONS = 1024;
    public static final int        SALT_SIZE        = 8;

    @Autowired
    private SystemFacadeService    systemFacadeService;
    @Autowired
    private SessionDAO             sessionDao;
    @Autowired
    private SystemAuthorizingRealm systemRealm;

    public SessionDAO getSessionDao() {
        return sessionDao;
    }

    /**
     * 根据登录名获取用户
     * 
     * @param loginName
     * @return
     */
    public User getUserByLoginName(String loginName) {
        return UserUtils.getByLoginName(loginName);
    }

    /**
     * 获得活动会话
     * 
     * @return
     */
    public Collection<Session> getActiveSessions() {
        return sessionDao.getActiveSessions(false);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // TODO Auto-generated method stub

    }

    public void updateUserLoginInfo(User user) {
        // 保存上次登录信息
        user.setOldLoginIp(user.getLoginIp());
        user.setOldLoginDate(user.getLoginDate());
        // 更新本次登录信息
        user.setLoginIp(StringUtils.getRemoteAddr(Servlets.getRequest()));
        user.setLoginDate(new Date());
        systemFacadeService.updateUserLoginInfo(user);
    }

}
